<template>
  <div class="search-page">
    <div class="page-container">
      <!-- 搜索头部 -->
      <div class="search-header">
        <div class="search-box">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索你感兴趣的内容..."
            size="large"
            class="search-input"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
            <template #append>
              <el-button @click="handleSearch" type="primary">
                搜索
              </el-button>
            </template>
          </el-input>
        </div>
        
        <!-- 搜索结果统计 -->
        <div v-if="hasSearched" class="search-stats">
          <span v-if="loading">搜索中...</span>
          <span v-else>
            找到 <strong>{{ total }}</strong> 个相关结果
            <span v-if="searchKeyword">关于 "<em>{{ searchKeyword }}</em>"</span>
          </span>
        </div>
      </div>
      
      <!-- 搜索结果 -->
      <div class="search-results">
        <!-- 加载状态 -->
        <div v-if="loading" class="loading-wrapper">
          <el-skeleton 
            v-for="i in 8" 
            :key="i" 
            animated 
            class="content-skeleton"
          >
            <template #template>
              <el-skeleton-item variant="image" style="width: 100%; height: 200px;" />
              <el-skeleton-item variant="h3" style="width: 50%" />
              <el-skeleton-item variant="text" style="width: 80%" />
            </template>
          </el-skeleton>
        </div>
        
        <!-- 搜索结果列表 -->
        <div v-else-if="contents.length > 0" class="waterfall-container">
          <div 
            v-for="content in contents" 
            :key="content.id" 
            class="content-card xhs-card fade-in"
            @click="goToDetail(content.id)"
          >
            <!-- 内容封面 -->
            <div class="card-cover">
              <img 
                v-if="content.fileUrl" 
                :src="content.fileUrl" 
                :alt="content.title"
                class="cover-image"
                @error="handleImageError"
              />
              <div v-else class="cover-placeholder">
                <el-icon><Document /></el-icon>
              </div>
              
              <!-- 悬浮操作按钮 -->
              <div class="card-actions">
                <div class="action-item" @click.stop="toggleLike(content)">
                  <el-icon :class="{ 'liked': content.isLiked }">
                    <StarFilled v-if="content.isLiked" />
                    <StarFilled v-else />
                  </el-icon>
                  <span>{{ content.likeCount || 0 }}</span>
                </div>
                <div class="action-item">
                  <el-icon><ChatLineRound /></el-icon>
                  <span>{{ content.commentCount || 0 }}</span>
                </div>
              </div>
            </div>
            
            <!-- 内容信息 -->
            <div class="card-content">
              <h3 class="content-title" v-html="highlightKeyword(content.title)"></h3>
              <p class="content-description" v-html="highlightKeyword(content.description)"></p>
              
              <!-- 标签 -->
              <div v-if="content.tags" class="content-tags">
                <span 
                  v-for="tag in content.tags.split(',')" 
                  :key="tag" 
                  class="xhs-tag"
                  v-html="highlightKeyword(tag.trim())"
                >
                </span>
              </div>
              
              <!-- 作者信息 -->
              <div class="author-info">
                <el-avatar :size="24" class="author-avatar">
                  <el-icon><User /></el-icon>
                </el-avatar>
                <span class="author-name">{{ content.authorName || '匿名用户' }}</span>
                <span class="publish-time">{{ formatTime(content.createdAt) }}</span>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 空状态 -->
        <div v-else-if="hasSearched && !loading" class="empty-state">
          <el-empty description="没有找到相关内容">
            <el-button type="primary" @click="clearSearch">
              清空搜索
            </el-button>
          </el-empty>
        </div>
        
        <!-- 默认状态 -->
        <div v-else class="default-state">
          <div class="default-content">
            <el-icon class="default-icon"><Search /></el-icon>
            <h3>搜索发现精彩内容</h3>
            <p>输入关键词，发现你感兴趣的内容</p>
            
            <!-- 热门搜索 -->
            <div class="hot-searches">
              <h4>热门搜索</h4>
              <div class="hot-tags">
                <el-tag 
                  v-for="tag in hotSearches" 
                  :key="tag"
                  @click="searchHotTag(tag)"
                  class="hot-tag"
                  effect="plain"
                >
                  {{ tag }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 加载更多 -->
      <div v-if="hasMore && contents.length > 0" class="load-more">
        <el-button 
          :loading="loading" 
          @click="loadMore"
          class="load-more-btn"
        >
          {{ loading ? '加载中...' : '加载更多' }}
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { searchContents, toggleLike as toggleLikeApi } from '@/api/content'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import 'dayjs/locale/zh-cn'
import { 
  Search, 
  Document, 
  StarFilled, 
  ChatLineRound, 
  User 
} from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()

// 配置dayjs
dayjs.extend(relativeTime)
dayjs.locale('zh-cn')

const searchKeyword = ref('')
const contents = ref([])
const loading = ref(false)
const hasSearched = ref(false)
const hasMore = ref(true)
const currentPage = ref(0)
const total = ref(0)
const pageSize = 12

// 热门搜索标签
const hotSearches = ref(['美食', '旅行', '时尚', '美妆', '健身', '摄影', '音乐', '读书'])

// 监听路由查询参数
watch(() => route.query.q, (newKeyword) => {
  if (newKeyword) {
    searchKeyword.value = newKeyword
    handleSearch()
  }
}, { immediate: true })

// 执行搜索
const handleSearch = async (page = 0) => {
  if (!searchKeyword.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }
  
  loading.value = true
  hasSearched.value = true
  
  try {
    const res = await searchContents({
      keyword: searchKeyword.value.trim(),
      page,
      size: pageSize
    })
    
    if (page === 0) {
      contents.value = res.data || []
      currentPage.value = 0
    } else {
      contents.value.push(...(res.data || []))
    }
    
    total.value = res.total || 0
    hasMore.value = res.data && res.data.length === pageSize
    
    // 更新URL
    if (page === 0) {
      router.replace({
        query: { q: searchKeyword.value.trim() }
      })
    }
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败')
  } finally {
    loading.value = false
  }
}

// 加载更多
const loadMore = () => {
  currentPage.value++
  handleSearch(currentPage.value)
}

// 清空搜索
const clearSearch = () => {
  searchKeyword.value = ''
  contents.value = []
  hasSearched.value = false
  total.value = 0
  router.replace({ query: {} })
}

// 搜索热门标签
const searchHotTag = (tag) => {
  searchKeyword.value = tag
  handleSearch()
}

// 跳转到详情页
const goToDetail = (id) => {
  router.push(`/content/${id}`)
}

// 高亮关键词
const highlightKeyword = (text) => {
  if (!searchKeyword.value || !text) return text
  
  const keyword = searchKeyword.value.trim()
  const regex = new RegExp(`(${keyword})`, 'gi')
  return text.replace(regex, '<mark class="highlight">$1</mark>')
}

// 点赞/取消点赞
const toggleLike = async (content) => {
  try {
    await toggleLikeApi(content.id)
    content.isLiked = !content.isLiked
    content.likeCount = content.isLiked 
      ? (content.likeCount || 0) + 1 
      : Math.max((content.likeCount || 1) - 1, 0)
    
    ElMessage.success(content.isLiked ? '点赞成功' : '取消点赞')
  } catch (error) {
    console.error('点赞操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 处理图片加载错误
const handleImageError = (event) => {
  event.target.style.display = 'none'
  const placeholder = event.target.parentNode.querySelector('.cover-placeholder')
  if (placeholder) {
    placeholder.style.display = 'flex'
  }
}

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).fromNow()
}
</script>

<style scoped lang="scss">
.search-page {
  min-height: 100vh;
  background-color: $bg-light;
  padding: $spacing-lg 0;
}

.page-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 $spacing-lg;
}

.search-header {
  margin-bottom: $spacing-xl;
  
  .search-box {
    max-width: 600px;
    margin: 0 auto $spacing-lg;
    
    .search-input {
      :deep(.el-input__wrapper) {
        border-radius: $border-radius-large;
      }
      
      :deep(.el-input-group__append) {
        border-radius: 0 $border-radius-large $border-radius-large 0;
      }
    }
  }
  
  .search-stats {
    text-align: center;
    color: $text-secondary;
    font-size: $font-size-sm;
    
    strong {
      color: $primary-color;
    }
    
    em {
      color: $text-primary;
      font-style: normal;
    }
  }
}

.search-results {
  .loading-wrapper {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
    grid-gap: $spacing-md;
    
    .content-skeleton {
      background: $bg-white;
      border-radius: $border-radius-large;
      padding: $spacing-md;
    }
  }
  
  .waterfall-container {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
    grid-gap: $spacing-md;
    
    .content-card {
      cursor: pointer;
      transition: all 0.3s ease;
      background: $bg-white;
      
      &:hover {
        transform: translateY(-4px);
        box-shadow: $shadow-medium;
        
        .card-actions {
          opacity: 1;
        }
      }
      
      .card-cover {
        position: relative;
        width: 100%;
        height: 200px;
        overflow: hidden;
        border-radius: $border-radius-large $border-radius-large 0 0;
        
        .cover-image {
          width: 100%;
          height: 100%;
          object-fit: cover;
          transition: transform 0.3s ease;
          
          &:hover {
            transform: scale(1.05);
          }
        }
        
        .cover-placeholder {
          width: 100%;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          background: $bg-light;
          color: $text-light;
          
          .el-icon {
            font-size: $spacing-xxl;
          }
        }
        
        .card-actions {
          position: absolute;
          top: $spacing-sm;
          right: $spacing-sm;
          display: flex;
          flex-direction: column;
          gap: $spacing-sm;
          opacity: 0;
          transition: opacity 0.3s ease;
          
          .action-item {
            display: flex;
            align-items: center;
            gap: $spacing-xs;
            background: rgba(255, 255, 255, 0.9);
            backdrop-filter: blur(10px);
            padding: $spacing-xs $spacing-sm;
            border-radius: $border-radius-large;
            font-size: $font-size-xs;
            color: $text-secondary;
            
            .el-icon {
              font-size: $font-size-sm;
              
              &.liked {
                color: $primary-color;
              }
            }
            
            &:hover {
              background: $bg-white;
            }
          }
        }
      }
      
      .card-content {
        padding: $spacing-md;
        
        .content-title {
          font-size: $font-size-md;
          font-weight: 600;
          color: $text-primary;
          margin-bottom: $spacing-sm;
          line-height: 1.4;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }
        
        .content-description {
          font-size: $font-size-sm;
          color: $text-secondary;
          margin-bottom: $spacing-sm;
          line-height: 1.5;
          display: -webkit-box;
          -webkit-line-clamp: 3;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }
        
        .content-tags {
          margin-bottom: $spacing-sm;
          
          .xhs-tag {
            margin-right: $spacing-xs;
            margin-bottom: $spacing-xs;
          }
        }
        
        .author-info {
          display: flex;
          align-items: center;
          gap: $spacing-sm;
          font-size: $font-size-xs;
          color: $text-light;
          
          .author-avatar {
            border: 1px solid $border-light;
          }
          
          .author-name {
            font-weight: 500;
            color: $text-secondary;
          }
          
          .publish-time {
            margin-left: auto;
          }
        }
      }
    }
  }
  
  .default-state {
    text-align: center;
    padding: $spacing-xxl 0;
    
    .default-content {
      max-width: 400px;
      margin: 0 auto;
      
      .default-icon {
        font-size: 80px;
        color: $text-light;
        margin-bottom: $spacing-lg;
      }
      
      h3 {
        color: $text-primary;
        margin-bottom: $spacing-sm;
      }
      
      p {
        color: $text-secondary;
        margin-bottom: $spacing-xl;
      }
      
      .hot-searches {
        h4 {
          color: $text-primary;
          margin-bottom: $spacing-md;
        }
        
        .hot-tags {
          display: flex;
          flex-wrap: wrap;
          gap: $spacing-sm;
          justify-content: center;
          
          .hot-tag {
            cursor: pointer;
            transition: all 0.3s ease;
            
            &:hover {
              background: $primary-color;
              color: white;
              border-color: $primary-color;
            }
          }
        }
      }
    }
  }
}

.load-more {
  text-align: center;
  margin-top: $spacing-xl;
  
  .load-more-btn {
    border-radius: $border-radius-large;
  }
}

// 高亮样式
:deep(.highlight) {
  background: linear-gradient(135deg, $primary-color 0%, $primary-light 100%);
  color: white;
  padding: 2px 4px;
  border-radius: $border-radius-small;
  font-weight: 500;
}

// 响应式设计
@media (max-width: $breakpoint-md) {
  .page-container {
    padding: 0 $spacing-md;
  }
  
  .waterfall-container {
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    grid-gap: $spacing-sm;
  }
}

@media (max-width: $breakpoint-sm) {
  .page-container {
    padding: 0 $spacing-sm;
  }
  
  .waterfall-container {
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
  }
  
  .search-header .search-box {
    max-width: 100%;
  }
}
</style> 